package com.cdy.common.uitl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;

public class FileUtil {


    public static FileChannel openChannel(File file) throws Exception {
        return FileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE);
    }

    public synchronized static File openFile(String name) throws Exception {
        File file = new File(name);
        if (!file.exists() && !file.createNewFile()) {
            throw new RuntimeException(name + " create fail !");
        }
        return file;
    }

    public static void write(FileChannel fileChannel, ByteBuffer byteBuffer, Long begin) throws Exception {
        fileChannel.write(byteBuffer, begin);
    }

    public static void closeChannel(FileChannel fileChannel) throws Exception {
        if (fileChannel != null) {
            fileChannel.close();
        }
    }

    public static ByteBuf readChannel(FileChannel channel, Long begin, int length) throws Exception {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(length);
        byteBuf.writeBytes(channel, begin, length);
        return byteBuf;
    }
}
